package com.lili.core.bridge;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import com.lili.core.log4lili.Logger;
import com.lili.core.log4lili.LoggerFactory;

public class ModuleRegistryFactoryBean implements FactoryBean, ApplicationContextAware, InitializingBean {
    @Override
    public Object getObject() throws Exception {
        return ModuleRegistry.getInstance();
    }

    @Override
    public Class<?> getObjectType() {
        return ModuleRegistry.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    //
    // register modules while root application context initializing.

    @Override
    public void afterPropertiesSet() throws Exception {
        ModuleRegistry registry = ModuleRegistry.getInstance();
        if (_moduleTypes != null) {
            for (Class<?> moduleType : _moduleTypes) {
                registry.registerModule(moduleType);
            }
        }
        _moduleTypes = null;
    }

    public void setModules(Class<?>[] value) {
        _moduleTypes = value;
    }

    private Class<?>[] _moduleTypes;

    //

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (_logger.isDebugEnabled()) {
            _logger.debug("Setting root application context. " + applicationContext);
        }
        ModuleRegistry registry = ModuleRegistry.getInstance();
        registry.setRootContext(applicationContext);
    }

    private transient static Logger _logger = LoggerFactory.getLogger(ModuleRegistryFactoryBean.class);
}
